#include <dirent.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include "object.h"
#include "util.h"
#include "dirops.h"
#include "cache.h"
#include "amazon.h"

void dump_dir (object *dir) {

  assert (dir->type == DIR_OBJ);

  printf ("Dumping the directory object\n");
  printf ("Name\t\t\t Object_ID\t Key\n");

  int count = dir->length/(sizeof (dentry));
  int i;

  for (i=0; i<count; i++) {

    dentry *d = (dentry *) (dir->data + (i*sizeof(dentry)));
    char c = (d->obj_id).type == DIR_OBJ ? 'd' : 'f';
    printf ("%s\t %c-%s %s-%s\n", d->name, c, 
         (d->obj_id).id, ((d->obj_id).key).key, ((d->obj_id).key).iv);
  }
}

void dump_file (object *file) {

  assert (file->type == FILE_OBJ);

  printf ("Dumping the file object\n");
  printf ("ObjectID\t\t\t Key\t\t\t Offset\t Size\n");

  int count = file->length/(sizeof (fentry));
  int i;

  for (i=0; i<count; i++) {

    fentry *f = (fentry *) (file->data + (i*sizeof (fentry)));
    //assert ((f->obj_id).type == DATA_OBJ);

    printf ("r-%s\t %s-%s %d\t %d\n", (f->obj_id).id, 
                    ((f->obj_id).key).key, ((f->obj_id).key).iv,
                    (int) f->offset, (int) f->size);

  }  
}

int main (int argc, char *argv[]) {


  if (argc != 3) {
    printf ("some usage goes here\n");
    return -1;

  }

  object obj;
  void *data = malloc (MAX_DATA_OBJ);

  int fd = open (argv[2], O_RDONLY);
  char arbit[64];
  read (fd, arbit, 64);
  obj.length = read (fd, data, MAX_DATA_OBJ);
  if (argv[1][0] == 'd')
    obj.type = DIR_OBJ;
  else if (argv[1][0] == 'f')
    obj.type = FILE_OBJ;
  else 
    obj.type = DATA_OBJ;

  obj.data = data;

  if (obj.type == DIR_OBJ)
    dump_dir (&obj);
  else
    dump_file (&obj);

  free (data);

  return 0;
}
